package com.ttx.test.app.basedata;

import cn.hutool.core.io.FileUtil;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 准备内存数据库中的数据
 * @author TimFruit
 * @date 19-11-17 上午10:50
 */
@Configuration
public class BaseDataConfig {
    public static final Logger logger=LoggerFactory.getLogger(BaseDataConfig.class);

    String dataPrefix= "databases/jpetstore/";

    //数据源
    @Bean("myDataSource")
    public DataSource createDataSource() {
        //创建数据源
        logger.info("创建数据源...");
        InputStream inputStream=FileUtil.getInputStream(dataPrefix+"jpetstore-hsql2mysql.properties");
        Properties properties=new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        HikariDataSource dataSource=new HikariDataSource();
        dataSource.setDriverClassName(properties.getProperty("driver"));
        dataSource.setJdbcUrl(properties.getProperty("url"));
        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));


        //准备数据
        logger.info("准备数据...");
        try {
            BaseDataTest.runScript(dataSource, dataPrefix+"jpetstore-mysql-schema.sql");
            BaseDataTest.runScript(dataSource, dataPrefix+"jpetstore-mysql-dataload.sql");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        logger.info("准备数据完成...");

        return dataSource;
    }




    // mapper
    @Bean
    public SqlSessionFactory createSqlSessionFactoryBean (
            @Qualifier("myDataSource") DataSource dataSource,
            @Autowired MybatisProperties mybatisProperties) throws Exception {

        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        if (!ObjectUtils.isEmpty(mybatisProperties.resolveMapperLocations())) {
            factory.setMapperLocations(mybatisProperties.resolveMapperLocations());
        }
        return factory.getObject();
    }




}
